package com.lsb.fitnessnutrition

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_food_search.*
import org.json.JSONObject
import org.tensorflow.lite.examples.classification.R
import java.math.BigInteger
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest

class FoodSearchActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_food_search)
    }

    fun md5(input:String): String {
        val md = MessageDigest.getInstance("MD5")
        return BigInteger(1, md.digest(input.toByteArray())).toString(16).padStart(32, '0')
    }

    fun search_button(view: View) {
        Thread()
        {

            var queryWord = search_food_text.text.toString()
            //将中文转为URL可以识别的类型
            var queryWordUrl = java.net.URLEncoder.encode(queryWord, "utf-8")
            Log.v("word",queryWord)
            Log.v("wordToUrl",queryWordUrl)
            val appid = "20201128000628383"
            val salt = "liusibo"
            val secretKey = "SiiFwhu8gph3OmPyhT_9"

            var md5Text = md5(appid+queryWord+salt+secretKey)

            Log.v("md5word",md5Text)

            val textJson = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" +
                    queryWordUrl +
                    "&from=auto&to=en&appid=20201128000628383&salt=liusibo&sign=" +
                    md5Text

            Log.v("EnglishTranslateJsonUrl",textJson)

            var connection = URL(textJson).openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            var inputstream = connection.inputStream
            var reader = inputstream.bufferedReader()
            var response = StringBuilder()
            while (true)
            {
                val line = reader.readLine()
                if (line == null)
                    break
                response.append(line)
            }


            val englishWord = JSONObject(response.toString()).getJSONArray("trans_result")
                .getJSONObject(0).getString("dst")

            Log.v("EnglishWord",englishWord)


            val url = "https://api.edamam.com/api/food-database/v2/parser?ingr=" +
                    englishWord.replace(" ","%20") +
                    "&app_id=a172dc35&app_key=ac3cfa696d5cd679017fdcbb78282f2b"

            Log.v("urlFirst",url)

            connection = URL(url).openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            inputstream = connection.inputStream
            reader = inputstream.bufferedReader()
            response = response.delete(0,response.length)  //清空response
            while (true)
            {
                val line = reader.readLine()
                if (line == null)
                    break
                response.append(line)
            }
            reader.close()
            connection.disconnect()
            Log.v("foodJson",response.toString())
            if(JSONObject(response.toString()).getJSONArray("parsed").isNull(0))
            {
                runOnUiThread{
                    textview.text = "No Data"
                    food_img.setImageResource(R.drawable.error)
                }
            }else {
                val label = "name : " + JSONObject(response.toString()).getJSONArray("parsed")
                    .getJSONObject(0).getJSONObject("food").getString("label") + "(per 100g)\n"

                val cal = "calorie : " + JSONObject(response.toString()).getJSONArray("parsed")
                    .getJSONObject(0).getJSONObject("food")
                    .getJSONObject("nutrients").getDouble("ENERC_KCAL") + "\n"

                val protein = "protein : " + JSONObject(response.toString()).getJSONArray("parsed")
                    .getJSONObject(0).getJSONObject("food")
                    .getJSONObject("nutrients").getDouble("PROCNT") + "\n"

                val fat = "fat : " + JSONObject(response.toString()).getJSONArray("parsed")
                    .getJSONObject(0).getJSONObject("food")
                    .getJSONObject("nutrients").getDouble("FAT") + "\n"

                val carbohydrate =
                    "carbohydrate : " + JSONObject(response.toString()).getJSONArray("parsed")
                        .getJSONObject(0).getJSONObject("food")
                        .getJSONObject("nutrients").getDouble("CHOCDF") + "\n"

                val fibre = "fibre : " + JSONObject(response.toString()).getJSONArray("parsed")
                    .getJSONObject(0).getJSONObject("food")
                    .getJSONObject("nutrients").getDouble("FIBTG") + "\n"

                //判断图片url是否为空
                if(JSONObject(response.toString()).getJSONArray("parsed")
                        .getJSONObject(0).getJSONObject("food").isNull("image")==false) {
                    val pictureUrl = JSONObject(response.toString()).getJSONArray("parsed")
                        .getJSONObject(0).getJSONObject("food").getString("image")
                    runOnUiThread {
                        textview.text = label + cal + protein + fat + carbohydrate + fibre
                        Picasso.get().load(pictureUrl).into(food_img)
                    }
                }
                else {
                    runOnUiThread {
                        textview.text = label + cal + protein + fat + carbohydrate + fibre
                    }
                }
            }
        }.start()
    }
}